import clsm from "@/lib/utils/clsm";
import { useEffect, useRef, type PropsWithChildren } from "react";

export default function LongScrollText(
  props: PropsWithChildren<{ className?: string; deps?: any[] }>,
) {
  const { children, className, deps = [] } = props;
  const elRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const currentScroll = useRef({ current: 0, max: 0 });

  useEffect(() => {
    let rfaTimer: number | undefined;
    let timeoutTimer: Timer | undefined;
    let d = 1;

    function check() {
      if (rfaTimer) {
        cancelAnimationFrame(rfaTimer);
        rfaTimer = undefined;
      }
      if (timeoutTimer) {
        clearTimeout(timeoutTimer);
        timeoutTimer = undefined;
      }
      const el = elRef.current!;
      const content = contentRef.current!;
      const { clientWidth } = el;
      const { clientWidth: scrollWidth } = content;
      currentScroll.current = { current: 0, max: scrollWidth - clientWidth };
      if (scrollWidth <= clientWidth) {
        contentRef.current!.style = "";
        return;
      }

      function scroll() {
        const { current, max } = currentScroll.current;
        let sleep = false;
        if (current >= max) {
          sleep = true;
          d = -1;
        } else if (current <= 0) {
          sleep = true;
          d = 1;
        }
        currentScroll.current = { current: current + d * 0.5, max };
        const x = currentScroll.current.current;
        contentRef.current!.style.left = `${-x}px`;
        if (sleep) {
          timeoutTimer = setTimeout(() => {
            rfaTimer = requestAnimationFrame(scroll);
            timeoutTimer = undefined;
          }, 1000);
        } else {
          rfaTimer = requestAnimationFrame(scroll);
        }
      }

      rfaTimer = requestAnimationFrame(scroll);
    }

    check();

    window.addEventListener("resize", check);

    return () => {
      rfaTimer && cancelAnimationFrame(rfaTimer);
      timeoutTimer && clearTimeout(timeoutTimer);
      window.removeEventListener("resize", check);
    };
  }, [...deps]); // eslint-disable-line

  return (
    <div
      className={clsm("overflow-hidden whitespace-nowrap", className)}
      ref={elRef}
    >
      <div className="relative w-max" ref={contentRef}>
        {children}
      </div>
    </div>
  );
}
